/**
 * 字典管理模块
 */
const {
	dictDataCollection
} = require('../../common/constants')
const {
	ERROR
} = require('../../common/error')
const {
	transformMultiLangData
} = require('../../lib/transform')

module.exports = {
	/**
	 * 获取字典数据列表
	 * @param {string} type 字典类型
	 * @param {object} options 查询选项
	 * @returns {object} 字典数据列表
	 */
	async getDictDatas(type, options = {}) {
		if (!type) {
			throw {
				errCode: ERROR.DICT_TYPE_REQUIRED
			}
		}
		
		try {
			const { status = 1, orderBy = 'sort', orderType = 'asc' } = options;
			
			const result = await dictDataCollection
				.where({
					dict_type: type,
					status: status
				})
				.orderBy(orderBy, orderType)
				.get();
			
			// 获取当前请求的语言
			const language = this.language || 'zh-Hans';
			
			// 使用通用转换方法转换数据格式
			const transformedData = transformMultiLangData(result.data, language, {
				multiLangFields: ['label', 'description'],
				keepFields: ['value', 'sort', 'icon', 'color', 'status', 'is_default', 'extra', 'create_time', 'update_time'],
				idMapping: { '_id': 'id' }
			});
			
			return {
				errCode: 0,
				data: transformedData
			}
		} catch (error) {
			throw {
				errCode: ERROR.DICT_GET_FAILED
			}
		}
	},
	
	/**
	 * 获取全量字典数据并按dict_type分组
	 * @returns {object} 按dict_type分组的字典数据Map
	 */
	async getAllDictDataMap() {
		try {
			// 查询所有启用状态的字典数据，按照 dict_type 和 sort 排序
			const result = await dictDataCollection
				.where({
					status: 1
				})
				.orderBy('dict_type', 'asc')
				.orderBy('sort', 'asc')
				.get();
			
			// 获取当前请求的语言
			const language = this.language || 'zh-Hans';
			
			// 使用通用转换方法转换数据格式
			const transformedData = transformMultiLangData(result.data, language, {
				multiLangFields: ['label', 'description'],
				keepFields: ['dict_type', 'value', 'sort', 'icon', 'color', 'status', 'is_default', 'extra', 'create_time', 'update_time'],
				idMapping: { '_id': 'id' }
			});
			
			// 按照 dict_type 分组
			const dictMap = {};
			transformedData.forEach(item => {
				const dictType = item.dict_type;
				if (!dictMap[dictType]) {
					dictMap[dictType] = [];
				}
				// 移除 dict_type 字段，避免冗余
				const { dict_type, ...itemWithoutType } = item;
				dictMap[dictType].push(itemWithoutType);
			});
			
			return {
				errCode: 0,
				data: dictMap
			}
		} catch (error) {
			throw {
				errCode: ERROR.DICT_GET_FAILED
			}
		}
	}
}
